package com.android.videotest.music.ui;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.media.AudioManager;
import android.os.Bundle;
import android.os.RemoteException;
import android.support.v4.media.MediaBrowserCompat;
import android.support.v4.media.MediaMetadataCompat;
import android.support.v4.media.session.MediaControllerCompat;
import android.support.v4.media.session.MediaSessionCompat;
import android.support.v4.media.session.PlaybackStateCompat;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;

import androidx.annotation.NonNull;

import com.android.videotest.R;
import com.android.videotest.music.MusicService;
import com.android.videotest.music.base.BaseMusicActivity;

import java.util.List;

public class MediaPlayerActivity extends BaseMusicActivity {
    private MediaBrowserCompat mediaBrowser;
    private static final String TAG = "MediaPlayerActivity-App";
    public static void start(Context context) {
        Intent starter = new Intent(context, MediaPlayerActivity.class);
//    starter.putExtra();
        context.startActivity(starter);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_media_player);
        // 创建MediaBrowserServiceCompat
        mediaBrowser = new MediaBrowserCompat(this,
                new ComponentName(this, MusicService.class),
                connectionCallbacks,
                null); // optional Bundle

    }

    @Override
    public void onStart() {
        super.onStart();
        mediaBrowser.connect();
    }

    @Override
    public void onResume() {
        super.onResume();
        setVolumeControlStream(AudioManager.STREAM_MUSIC);
    }

    @Override
    public void onStop() {
        super.onStop();
        // (see "stay in sync with the MediaSession")
        if (MediaControllerCompat.getMediaController(MediaPlayerActivity.this) != null) {
            MediaControllerCompat.getMediaController(MediaPlayerActivity.this).unregisterCallback(controllerCallback);
        }
        mediaBrowser.disconnect();

    }

    @Override
    protected void onConnected(@NonNull MediaControllerCompat mediaController) {

    }

    @Override
    protected void onChildrenLoaded(@NonNull String parentId, @NonNull List<MediaBrowserCompat.MediaItem> children) {

    }

    @Override
    protected void onDisconnected() {

    }

    @Override
    protected void onPlaybackStateChanged(PlaybackStateCompat state) {

    }

    @Override
    protected void onMetadataChanged(MediaMetadataCompat metadata) {

    }

    private final MediaBrowserCompat.ConnectionCallback connectionCallbacks =
            new MediaBrowserCompat.ConnectionCallback() {
                @Override
                public void onConnected() {
                    Log.d(TAG, "onConnected() called");
                    try {
                        //获取MediaSession的令牌
                        MediaSessionCompat.Token token = mediaBrowser.getSessionToken();
                        // 创建一个MediaControllerCompat
                        MediaControllerCompat mediaController = new MediaControllerCompat(MediaPlayerActivity.this, token);
                        // 保存控制器
                        MediaControllerCompat.setMediaController(MediaPlayerActivity.this, mediaController);
                        // 完成构建UI
                        buildTransportControls();
                        mediaBrowser.subscribe(mediaBrowser.getRoot(), new MediaBrowserCompat.SubscriptionCallback() {
                            @Override
                            public void onChildrenLoaded(@NonNull String parentId, @NonNull List<MediaBrowserCompat.MediaItem> children) {
                                Log.d(TAG, "onChildrenLoaded() called with: parentId = [" + parentId + "], children = [" + children + "]");

                            }

                            @Override
                            public void onError(@NonNull String parentId) {
                                super.onError(parentId);
                                Log.d(TAG, "onError() called with: parentId = [" + parentId + "]");
                            }

                            @Override
                            public void onError(@NonNull String parentId, @NonNull Bundle options) {
                                super.onError(parentId, options);
                                Log.d(TAG, "onError() called with: parentId = [" + parentId + "], options = [" + options + "]");
                            }
                        });
                    } catch (RemoteException e) {

                    }
                }

                @Override
                public void onConnectionSuspended() {
                    Log.d(TAG, "onConnectionSuspended() called");
                    // 服务已崩溃。禁用传输控件，直到它自动重新连接
                }

                @Override
                public void onConnectionFailed() {
                    Log.d(TAG, "onConnectionFailed() called");
                    // 服务已拒绝我们的连接
                }
            };

    void buildTransportControls() {
        // 抓住视图的播放/暂停按钮
        ImageView playPause = findViewById(R.id.play_pause);
        // 将监听器附加到按钮
        playPause.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 由于这是一个播放/暂停按钮，因此您需要测试当前状态并相应地选择操作
                PlaybackStateCompat playbackState = MediaControllerCompat.getMediaController(MediaPlayerActivity.this).getPlaybackState();
                if (playbackState != null) {
                    int pbState = playbackState.getState();
                    if (pbState == PlaybackStateCompat.STATE_PLAYING) {
                        MediaControllerCompat.getMediaController(MediaPlayerActivity.this).getTransportControls().pause();
                    } else {
                        MediaControllerCompat.getMediaController(MediaPlayerActivity.this).getTransportControls().play();
                    }
                }
            }
        });
        MediaControllerCompat mediaController = MediaControllerCompat.getMediaController(MediaPlayerActivity.this);
        // 显示初始状态
        MediaMetadataCompat metadata = mediaController.getMetadata();
        PlaybackStateCompat pbState = mediaController.getPlaybackState();
        // 注册回调以保持同步
        mediaController.registerCallback(controllerCallback);
    }

    MediaControllerCompat.Callback controllerCallback =
            new MediaControllerCompat.Callback() {
                @Override
                public void onMetadataChanged(MediaMetadataCompat metadata) {
                    Log.d(TAG, "onMetadataChanged: " + metadata.getString(MediaMetadataCompat.METADATA_KEY_TITLE));
                    Log.d(TAG, "onMetadataChanged() called with: metadata = [" + metadata + "]");
                }

                @Override
                public void onPlaybackStateChanged(PlaybackStateCompat state) {
                    Log.d(TAG, "onPlaybackStateChanged() called with: state = [" + state + "]");
                }
            };


}